package com.stone.framework.batch.tasklet;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterUtils;
import org.springframework.util.Assert;

/**
 * SQL tasklet
 * 
 * @author ybliu
 * @date 2020/07/27
 */
public class JdbcTemplateTasklet implements Tasklet, InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(JdbcTemplateTasklet.class);

    private String[] sqls;
    private Map<String, Object> paramMap = new HashMap<>();
    private DataSource dataSource;

    private JdbcTemplate jdbcTemplate;

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
        Stream.of(this.sqls).peek(LOGGER::info)
            .forEach(sql -> this.jdbcTemplate.update(sql, NamedParameterUtils.buildValueArray(sql, this.paramMap)));
        contribution.setExitStatus(ExitStatus.COMPLETED);
        return RepeatStatus.FINISHED;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.dataSource, "dataSource must not be null");
        Assert.notNull(this.sqls, "sqls must not be null");
        this.jdbcTemplate = new JdbcTemplate(this.dataSource);
    }

    public void setSqls(String... sqls) {
        this.sqls = sqls;
    }

    public void setParamMap(Map<String, Object> paramMap) {
        this.paramMap = paramMap;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

}
